package p.jce;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class BC {
	private static final Map<String, String> properties;
	static {
		try {
			Properties p = new Properties();
			p.load(BC.class.getResourceAsStream("BC.txt"));
			HashMap<String, String> map = new HashMap<String, String>();
			for (String s : p.stringPropertyNames()) {
				map.put(s, p.getProperty(s));
			}
			properties = Collections.unmodifiableMap(map);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	private static String getAlias(String prefix, String alg) {
		return properties.get("Alg.Alias." + prefix + "." + alg);
	}

	private static ClassLoader cl;

	public static void setClassLoader(ClassLoader xcl) {
		cl = xcl;
	}

	@SuppressWarnings("unchecked")
	private static <T> Class<T> getClass(String prefix, String algorithm) throws ClassNotFoundException {
		String nAlg = getAlias(prefix, algorithm);
		if (nAlg == null) {
			nAlg = algorithm;
		}
		String clz = properties.get(prefix + "." + nAlg);
		if (clz == null) {
			new NoSuchAlgorithmException(algorithm);
		}
		if (cl == null) {
			cl = Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider").getClassLoader();
		}
		return (Class<T>) cl.loadClass(clz);
	}

	@SuppressWarnings("unchecked")
	public static <T> T newInstance(String prefix, String algorithm) throws InstantiationException,
			IllegalAccessException, ClassNotFoundException {
		return (T) getClass(prefix, algorithm.toUpperCase()).newInstance();
	}

}
